package com.mentalhealthplatform.global.log;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 这货不是酷盖
 */
@RestController
public class LogController {

    @Value("${logging.file.name}")
    private String logFilePath;

    private final ObjectMapper objectMapper = new ObjectMapper();

    // 读取日志内容并返回 JSON 格式的日志列表
    @GetMapping("/api/logs")
    public List<LogEntry> getLogs(@RequestParam(required = false, defaultValue = "100") int limit) throws IOException {
        List<String> lines = Files.readAllLines(Paths.get(logFilePath));
        List<LogEntry> logEntries = new ArrayList<>();

        // 逐行读取日志文件并解析为 LogEntry 对象
        for (int i = Math.max(lines.size() - limit, 0); i < lines.size(); i++) {
            String logLine = lines.get(i).trim();
            if (!logLine.isEmpty()) {
                try {
                    LogEntry logEntry = objectMapper.readValue(logLine, LogEntry.class);
                    logEntries.add(logEntry);
                } catch (Exception e) {
                    System.err.println("日志解析错误: " + e.getMessage() + " 行内容: " + logLine);
                }
            }
        }

        // 返回 JSON 格式的日志列表
        return logEntries;
    }
}
